package com.zpark.cglib;

import com.sun.org.apache.xpath.internal.Arg;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @PackageName: com.zpark.cglib
 * @ClassName: CglibProxy2
 * @Description:
 * @author: RZS
 * @date: 2023/3/30  9:56
 */
public class CglibProxy2 implements MethodInterceptor {
    // 定义切面类
    private CglibAspect aspect = new CglibAspect();

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        aspect.myBefore();
        Object invoke = method.invoke(new IAdminDao(), objects);
        aspect.myAfter();

        return invoke;
    }

    // 定义获取被代理的目标对象
    private Object getTarget(Object objTarget){
        Enhancer enhancer = new Enhancer();
        // 指定父类
        enhancer.setSuperclass(objTarget.getClass());
        // 设置回调
        enhancer.setCallback(this);
        // 创建代理目标对象
        Object o = enhancer.create();
        return o;
    }

    public static void main(String[] args) {
        CglibProxy2 proxy2 = new CglibProxy2();
        IAdminDao target = (IAdminDao) proxy2.getTarget(new IAdminDao());
        target.add();
    }
}
